# coding:utf8
'''
    新闻相关
'''
from flask_restful import Resource, request
from _sys.parser import parsers
from _sys.models import MongodbOperations, ResponseJson, Token, CreateId, FormatIO
from _sys.code import dbNameDict
from _sys.function import allow_cross, admin_open_ips, had_power,format_words, parse_param_info


import time

mgOp = MongodbOperations()
responseJson = ResponseJson()
token = Token()
cId = CreateId()

class News(Resource):
    '''
        /news
        -- get 获取新闻列表 详情
        -- post  修改新闻内容
        -- put 新增新闻
        --delete 删除新闻
    '''
    @allow_cross
    def get(self):
        args = parsers()
        w_news = args.get('w_id')
        pg = args.get('pg')      # 页码
        num = args.get('num')   # 单页显示数量
        start_t = args.get('start_t')
        end_t = args.get('end_t')
        status = args.get('status')

        if w_news:   # 获取单个新闻
            rd = mgOp.find_one(dbNameDict['newsData'], filter={'w_news':w_news})
            return responseJson.correct(code='ok', data=rd)
        else:   # 列表
            if not pg:
                pg = 1
            pg = int(pg)
            if not num:
                num = 24
            num = int(num)
            filter = {}
            time_query ={}
            if start_t:
                time_query["$gte"] = str(time.mktime(time.strptime(start_t, "%Y-%m-%d-%H:%M:%S")))
                filter['create_time'] = time_query
            if end_t:
                time_query["$lte"] = str(time.mktime(time.strptime(end_t, "%Y-%m-%d-%H:%M:%S")))
                filter['create_time'] = time_query
            if status:
                filter['news_status'] = status
            #print(filter)
            rds = mgOp.find_many(dbNameDict['newsData'], filter)[(pg-1)*num:pg*num]
            for rd in rds:
                rd['create_admin'] = rd['create_admin']
            return responseJson.correct(code='ok', data=rds)

    @allow_cross
    def post(self):
        '''
            修改新闻内容
        :return:
        '''
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        w_news = args.get('w_id')

        news_title = args.get('title')  # 标题
        new_banner = args.get('img')  # 新闻轮播图
        html_cn = args.get('cn')  # 内容
        html_tw = args.get('tw')  # 内容
        html_en = args.get('en')  # 内容
        news_status = args.get('status')  # 新闻状态
        new_tags = args.get('tags')  # 新闻标签

        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']

        if not had_power('CanModifyNews', powers):
            return responseJson.error_response(code='permissionsValidationFailure')

        if news_status == '1':
            publish_time = time.strftime("%Y-%m-%d %H:%M:%S" ,time.localtime()),
        else:
            publish_time = '--'

        new_news_data = {
            'news_title': format_words(parse_param_info(news_title)),
            'html_cn': html_cn,
            'html_tw': html_tw,
            'html_en': html_en,
            'new_banner': parse_param_info(new_banner),
            'new_tags': parse_param_info(new_tags),
            'news_status': news_status,
            'publish_time': publish_time
        }
        if new_news_data:
            if mgOp.update_one(dbNameDict['newsData'], filter={'w_news':w_news}, data=new_news_data):
                return responseJson.correct(code='ok', data={'msg':'修改新闻信息成功'})
            else:
                return responseJson.error_response(code='unknownError')
        else:
            return responseJson.error_response(code='lackOfNecessaryParameters')

    @allow_cross
    def put(self):
        '''
            新增新闻内容
        :return:
        '''
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr

        news_title = args.get('title')  # 标题
        new_banner = args.get('img')   # 新闻轮播图
        html_cn = args.get('cn')  # 内容
        html_tw = args.get('tw')  # 内容
        html_en = args.get('en')  # 内容
        news_status = args.get('status')  # 新闻状态
        new_tags = args.get('tags')    # 新闻标签

        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']

        if not had_power('CanAddNews', powers):   # 不具权限
            return responseJson.error_response(code='permissionsValidationFailure')

        w_news = cId.otherid()
        if news_status == '1':
            publish_time = time.strftime("%Y-%m-%d %H:%M:%S" ,time.localtime()),
        else:
            publish_time = '--'
        #print(news_title)
        news_data = {
            'w_news':w_news,
            'news_title':format_words(parse_param_info(news_title)),
            'html_cn':html_cn,
            'html_tw': html_tw,
            'html_en': html_en,
            'new_banner':parse_param_info(new_banner),
            'new_tags':parse_param_info(new_tags),
            'news_status':news_status,
            'create_time':str(time.time()),
            'format_time': FormatIO().timestamp_format(time.time()),
            'create_admin':a_id,
            'sub_time': time.strftime("%b %d %Y" ,time.localtime()),
            'publish_time': publish_time
        }
        try:
            mgOp.insert_one(dbNameDict['newsData'], news_data)
            return responseJson.correct(code='ok', data={'msg': '新增新闻成功'})
        except Exception:
                return responseJson.error_response(code='unknownError')

    @allow_cross
    def delete(self):
        '''
            根据w_news 删除指定新闻
        :return:
        '''
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        w_news = args.get('w_news')

        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']

        if not had_power('CanDeleteNews', powers):   # 不具权限
            return responseJson.error_response(code='permissionsValidationFailure')

        if w_news:
            if mgOp.delete_one(dbNameDict['newsData'], filter={'w_news':w_news}):
                return responseJson.correct(code='ok', data={'msg':'删除新闻信息成功'})
            else:
                return responseJson.error_response(code='unknownError')
        else:
            return responseJson.error_response(code='lackOfNecessaryParameters')







